package guestbook.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XMLParser {

	public static String fetchMeSomeXML(String urlString) {
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		InputStream in = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			in = new URL(urlString).openConnection().getInputStream();
			doc = docBuilder.parse(in);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

		if (doc == null)
			return "Failed to fetch " + urlString;

		NodeList nodes_i = doc.getDocumentElement().getChildNodes();
		for (int i = 0; i < nodes_i.getLength(); i++) {
			Node node_i = nodes_i.item(i);
			if (node_i.getNodeType() == Node.ELEMENT_NODE
					&& ((Element) node_i).getTagName().equals("body")) {
//				Element note = (Element) node_i;
//				NodeList nodes_j = note.getChildNodes();
//				for (int j = 0; j < nodes_j.getLength(); j++) {
//					Node node_j = nodes_j.item(j);
//					if (node_j.getNodeType() == Node.ELEMENT_NODE
//							&& ((Element) node_j).getTagName().equals("body")) {
						return node_i.getFirstChild().getNodeValue();
//					}
//				}
			}
		}
		
		return "couldn't find body";
	}

	// ...
	private String fetch(String urlString) {
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlString);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;

			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			reader.close();

		} catch (MalformedURLException e) {
			// ...
		} catch (IOException e) {
			// ...
		}
		return sb.toString();
	}
}
